package library;

import com.gooddies.swing.JpSplitPanel;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import library.books_author.BookAuthorPanel;
import library.model.BooksAuthorPojo;

/**
 * @author Dmitry
 */
public class ByGenrePanel extends JPanel {
    private GenresTree genresTree;
    private BookAuthorPanel booksAuthorPanel;
    private BookDescriptionPanel descriptionPanel;
    private DownloadPanel downloadPanel;

    public ByGenrePanel() {
        init();
    }

    private void init() {
        setLayout(new BorderLayout());
        JpSplitPanel horSplitPanel = new JpSplitPanel("genre.horSplitPanel");
        add(horSplitPanel);

        JPanel genresPanel = genresPanel();
        horSplitPanel.setLeftComponent(genresPanel);

        booksAuthorPanel = createBooksAuthorPanel();
        JpSplitPanel verSplitPanel = new JpSplitPanel("genre.verSplitPanel");
        verSplitPanel.setOrientation(JSplitPane.VERTICAL_SPLIT);
        verSplitPanel.setTopComponent(booksAuthorPanel);
        horSplitPanel.setRightComponent(verSplitPanel);

        genresTree.setGenreSelectedEvent(new GenresTree.OnGenreSelected() {
            @Override
            public void genreSelected(String genreId) {
                onGenreSelected(genreId);
            }
        });

        JpSplitPanel bottomHorSplitPanel = new JpSplitPanel("genre.bottomHorSplitPanel");
        verSplitPanel.setBottomComponent(bottomHorSplitPanel);

        descriptionPanel = new BookDescriptionPanel();
        descriptionPanel.setOnDownloadEvent(new BookDescriptionPanel.OnDownload() {
            @Override
            public void onDownload(BooksAuthorPojo toBeDownload) {
                ByGenrePanel.this.onDownload(toBeDownload);
            }
        });
        bottomHorSplitPanel.setRightComponent(descriptionPanel);
        downloadPanel = new DownloadPanel();
        bottomHorSplitPanel.setLeftComponent(downloadPanel);
    }

    private JPanel genresPanel() {
        JPanel panel = new JPanel();
        panel.setOpaque(true);
        genresTree = new GenresTree();
        genresTree.fillTree();
        JScrollPane scroll = new JScrollPane();
        scroll.getViewport().add(genresTree);
        panel.setLayout(new BorderLayout());
        panel.add(scroll);
        return panel;
    }

    private BookAuthorPanel createBooksAuthorPanel() {
        BookAuthorPanel panel = new BookAuthorPanel();
        panel.setOnBookAuthorSelectedEvent(new BookAuthorPanel.OnBookAuthorSelected() {
            @Override
            public void onSelect(BooksAuthorPojo object) {
                descriptionPanel.setBookAuthorObject(object);
            }
        });
        return panel;
    }
    
    private void onDownload(BooksAuthorPojo obj)    {
        downloadPanel.download(obj);
    }
    private void onGenreSelected(String genre) {
        booksAuthorPanel.setGenreFilter(genre);
    }
}
